package cn.ihoway.socket;

import cn.ihoway.entity.Allocation;
import cn.ihoway.redis.AllocationRedis;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class GameSessionManager {
    /**
     * 保存连接 session 的地方
     */
    private static ConcurrentHashMap<String, WebSocketSession> SESSION_POOL = new ConcurrentHashMap<>();
    private static final AllocationRedis allocationRedis = new AllocationRedis();

    /**
     * 添加 session
     */
    public static void add(String key, WebSocketSession session) {
        // 添加 session
        SESSION_POOL.put(key, session);
    }

    /**
     * 删除 session,会返回删除的 session
     */
    public static WebSocketSession remove(String key) {
        // 删除 session
        return SESSION_POOL.remove(key);
    }

    /**
     * 删除并同步关闭连接
     */
    public static void removeAndClose(String key) {
        WebSocketSession session = remove(key);
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                // todo: 关闭出现异常处理
                e.printStackTrace();
            }
        }
    }

    /**
     * 获得指定 session
     *
     */
    public static WebSocketSession get(String key) {
        // 获得 session
        return SESSION_POOL.get(key);
    }

    /**
     * 获取指定房间内全部用户
     */
    public static ArrayList<WebSocketSession> getFromRoom(String roomId){
        List<Allocation> list = allocationRedis.getByRoomId(roomId);
        ArrayList<WebSocketSession> resList = new ArrayList<>();
        for (Allocation allocation : list){
            WebSocketSession session = get(allocation.getSessionId());
            if(session != null){
                resList.add(session);
            }
        }
        return resList;
    }

    /**
     * 获取指定房间内全部用户
     */
    public static ArrayList<WebSocketSession> getAll(){
        return new ArrayList<>(SESSION_POOL.values());
    }

}

